"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 故障&可靠性测试
Case Name   : 重复dump不存在表
Create At   : 2021/04/30
@zou_jialiang0505328126
Description :
    1. 重复1w次导出不存在表
    2.查看内存使用情况
Expect      :
History     :
    modified: 2021/05/17  modified by @wan005,增加打印信息
"""

import os
import unittest
from yat.test import macro
from yat.test import Node
from testcase.utils.CommonSH import RestartDbCluster
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class Dump(unittest.TestCase):
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('Opengauss_Reliability_Tools_Dump_Case001.py 开始执行')
        self.db_primary_db_user = Node(node='PrimaryDbUser')
        self.db_primary_root = Node(node='PrimaryRoot')
        self.Constant = Constant()
        self.parent_path = os.path.dirname(macro.DB_INSTANCE_PATH)
        self.backup_file = os.path.join(self.parent_path, 'dump.txt')

    def test_basebackup(self):
        self.log.info('--------重复1w次导出不存在表------------------')
        cmd = f"source {macro.DB_ENV_PATH};" \
            f"gs_dump  -p {self.db_primary_db_user.db_port} " \
            f"{self.db_primary_db_user.db_name} -f {self.backup_file} " \
            f"-t tb_not_exist"
        self.log.info(cmd)
        for i in range(10000):
            self.log.info(f'-----------round {i}-------------')
            result = self.db_primary_db_user.sh(cmd).result()
            self.log.info(result)
            self.assertIn('no matching tables were found for '
                          'pattern "tb_not_exist"', result)
            self.assertIn('No matching tables were found', result)

        self.log.info('-------------检查内存------------')
        cmd = 'free -g'
        result = self.db_primary_root.sh(cmd).result()
        self.log.info(result)
        self.assertGreater(int(result.splitlines()[1].split(' ')[-1]), 0)

    def tearDown(self):
        self.log.info('-------------------------环境清理------------------------')
        self.log.info('--------------------------删除备份文件------------------')
        shell_cmd = f'rm -rf {self.backup_file}'
        self.log.info(shell_cmd)
        result = self.db_primary_db_user.sh(shell_cmd).result()
        self.log.info(result)
        self.log.info('Opengauss_Reliability_Tools_Dump_Case001.py 执行结束')
